<?php
abstract class XA_ListView {

	public $query;
	public $page = 1;
	public $count = 20;
	public $page_count = null;
	public $row_list = array();



	public function __construct($query = null) {
		if (is_a($query, 'XA_Query')) {
			$this->query = $query;
		} else {
			$this->row_list = $query;
		}
	}



	public function prepareRows() {
		return true;
	}



	public function getOutput() {
		return $this->out();
	}



	public function out() {
		if ($this->query) {
			$this->query->limit = $this->count;
			$this->query->offset = $this->count ? (($this->page - 1) * $this->count) : null;
			
			$count_query = clone $this->query;
			$count_query->fields = array('count' => 'COUNT(1)');
			$count_query->offset = $count_query->limit = $count_query->order_rules = null;
			$count_result = xa::query($count_query);
			$row_count = ($count_result->count() > 1) ? $count_result->count() : $count_result->val();
			$this->page_count = $this->count ? (int)ceil($row_count / $this->count) : 1;
			$this->row_list = xa::query($this->query)->all((isset($this->pk_list) && count($this->pk_list) === 1) ? $this->pk_list[0] : null);
			$this->prepareRows();
		} elseif (!$this->page_count) {
			$this->page_count = 1;
		}
	}
}
